package server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import action.Action;
import util.CmdParser;

public class TCPServer {
	public void start() throws Exception {
		ServerSocket server = new ServerSocket(8888);
		System.out.println("TCP Server started...");
		Socket socket = server.accept();
		System.out.println("TCP Server waitting...");
		OutputStream outputStream = socket.getOutputStream();
		InputStream inputStream = socket.getInputStream();
		outputStream.write("Pls input your command -->".getBytes());
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String command;
		while((command=reader.readLine())!=null){
			
			System.out.println("[command]"+command);
			
			System.out.println("TCP server received the command: "+command);
				String[] ss = CmdParser.parseCmd(command);
				if(ss==null){
					outputStream.write("Your command is invalid, please input again!\r\n".getBytes());
					System.out.println("command is invalid");
				}else{
					StringBuilder outString = new Action().action(ss[0],ss[1], ss[2]);
					outString.append("\r\nPls input your command -->");
					outputStream.write(outString.toString().getBytes());
					System.out.println("command is valid");
				}
		}
		inputStream.close();
		outputStream.close();
		socket.close();
		server.close();
	}
	
	public static void main(String[] args) throws Exception {
		new TCPServer().start();
	}

}
